package com.ds.common.route.config;

import com.ds.common.nacos.ConfigModel;
import lombok.Getter;
import lombok.Setter;
import org.mvel2.MVEL;

import java.io.Serializable;

public class ClusterConfig implements ConfigModel {

    /**
     * 集群名称
     */
    @Setter
    @Getter
    String name;

    /**
     * 优先级
     */
    @Setter
    @Getter
    int priority;
    /**
     * 命中条件
     */
    @Getter
    String condition;
    /**
     * 编译之后的表达式
     */
    @Getter
    Serializable conditionExpression;

    public static final ClusterConfig DEFAULT;

    static {
        DEFAULT = new ClusterConfig();
        DEFAULT.setName("renkang");
        DEFAULT.setPriority(0);
        DEFAULT.setCondition("agentId==0");
    }

    public void setCondition(String condition) {
        this.condition = condition;
        try {
            this.conditionExpression = MVEL.compileExpression(condition);
        } catch (Exception ex) {
            throw new RuntimeException("condition compile error~" + condition);
        }
    }

    @Override
    public boolean isValid() {
        // 成员不能为空
        return this.name != null && this.condition != null && this.conditionExpression != null;
    }
}
